package juc.demo;


import java.util.concurrent.*;

/**
 * 线程池: 提供了一个线程队列，队列中保存着所有等待状态的线程。避免了创建与销毁线程的额外开销，提高了响应的速度
 */
public class TestThreadPool {

    private static int k = 0;

    public static void main(String[] args) {

        // 手动创建线程池(使用了com.google.guava包)
//        ThreadFactory nameThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

//
//        ExecutorService pool = new ThreadPoolExecutor(5,200,0L,TimeUnit.MILLISECONDS,
//                new LinkedBlockingDeque<Runnable>(1024),new ThreadPoolExecutor.AbortPolicy());


        // 1. 创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
//
//        ThreadPoolDemo tpd = new ThreadPoolDemo();
//
//
        // 2. 为线程池中的线程分配任务
        for (int i = 0; i < 10; i++) {
            pool.submit(() -> {
                    System.out.println(Thread.currentThread().getName() + ":" + k++);
            });

//            pool.execute(tpd);
        }

        // 3. 关闭线程池
        pool.shutdown();

    }

}


class ThreadPoolDemo implements Runnable{

    private int i = 0;

    @Override
    public void run() {
        while (i <= 100) {
            System.out.println(Thread.currentThread().getName() + ":" + i++);
        }
    }
}
